import 'package:flutter/material.dart';

class RouteService extends NavigatorObserver {
  static RouteService get observer => _instance;
  static final RouteService _instance = RouteService._internal();
  final Map<String, dynamic> routes = {};
  RouteService._internal();

  @override
  void didPop(Route route, Route? previousRoute) {
    super.didPop(route, previousRoute);
    if (route.settings.name != null && route.settings.name!.isNotEmpty) {
      routes.remove(route.settings.name);
    }
  }

  @override
  void didPush(Route route, Route? previousRoute) {
    super.didPush(route, previousRoute);
    if (route.settings.name != null && route.settings.name!.isNotEmpty) {
      routes[route.settings.name!] = route.settings.name;
    }
  }

  @override
  void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    final newRouteName = newRoute?.settings.name;
    final oldRouteName = oldRoute?.settings.name;
    if (newRouteName != null &&
        newRouteName.isNotEmpty &&
        oldRouteName != null &&
        oldRouteName.isNotEmpty) {
      routes.remove(oldRouteName);
      routes[newRouteName] = newRouteName;
    }
  }

  @override
  void didRemove(Route route, Route? previousRoute) {
    super.didRemove(route, previousRoute);
    if (route.settings.name != null && route.settings.name!.isNotEmpty) {
      routes.remove(route.settings.name);
    }
  }

  bool isTopPage(String routeName){
    return RouteService.observer.routes.values.last == routeName;
  }

}
